package com.mall.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.constant.JwtClaimsConstant;
import com.mall.constant.MessageConstant;
import com.mall.constant.PasswordConstant;
import com.mall.constant.StatusConstant;
import com.mall.context.BaseContext;
import com.mall.dto.EmpEditPasswordDTO;
import com.mall.dto.EmployeeDTO;
import com.mall.dto.EmployeeLoginDTO;
import com.mall.dto.EmployeePageQueryDTO;
import com.mall.exception.BaseException;
import com.mall.po.Employee;
import com.mall.mapper.EmployeeMapper;
import com.mall.properties.JwtProperties;
import com.mall.result.PageResult;
import com.mall.service.EmployeeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.utils.JwtUtil;
import com.mall.vo.EmployeeLoginVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 员工信息 服务实现类
 * </p>
 *
 * @author itlxc
 * @since 2024-04-18
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    private final EmployeeMapper employeeMapper;
    private final JwtProperties jwtProperties;

    /**
     * 员工登录
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public EmployeeLoginVO login(EmployeeLoginDTO employeeLoginDTO) {
        // 判断用户名是否存在
        Employee employee = lambdaQuery()
                            .eq(Employee::getUsername, employeeLoginDTO.getUsername())
                            .one();
        if (Objects.isNull(employee)) {
            throw new BaseException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        // 判断密码是否正确
        String password = DigestUtils.md5DigestAsHex(employeeLoginDTO.getPassword().getBytes());
        if (!Objects.equals(password, employee.getPassword())) {
            throw new BaseException(MessageConstant.PASSWORD_ERROR);
        }
        // 判断员工状态是否禁用
        if (Objects.equals(employee.getStatus(), StatusConstant.DISABLE)) {
            throw new BaseException(MessageConstant.ACCOUNT_LOCKED);
        }
        // 登录成功生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), claims);
        log.info("登录成功,生成token：{}", token);
        // 封装vo
        return EmployeeLoginVO.builder()
                                .id(employee.getId())
                                .name(employee.getName())
                                .token(token)
                                .username(employee.getUsername())
                                .build();
    }

    /**
     * 员工分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult employeePageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        String name = employeePageQueryDTO.getName();
        // 分页条件
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<Employee>()
                .like(StringUtils.isNotBlank(name), Employee::getName, name)
                .orderByDesc(Employee::getUpdateTime);
        Page<Employee> page = page(new Page<>(employeePageQueryDTO.getPage(),
                employeePageQueryDTO.getPageSize()), queryWrapper);
        return new PageResult(page.getTotal(), page.getRecords());
    }

    /**
     * 新增员工
     * @param employeeDTO
     */
    @Override
    public void saveEmployee(EmployeeDTO employeeDTO) {
        Employee employee = BeanUtil.copyProperties(employeeDTO, Employee.class);
        // 员工默认状态为禁用
        employee.setStatus(StatusConstant.DISABLE);
        // 设置默认密码
        String password = DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes());
        employee.setPassword(password);
        save(employee);
    }

    /**
     * 修改密码
     * @param editPasswordDTO
     */
    @Override
    public void EmpEditPassword(EmpEditPasswordDTO editPasswordDTO) {
        Long empId = BaseContext.getCurrentId();
        Employee employee = getById(empId);
        // 判断旧密码是否正确
        String oldPassword = editPasswordDTO.getOldPassword();
        oldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        if (!Objects.equals(oldPassword, employee.getPassword())) {
            throw new BaseException(MessageConstant.PASSWORD_EDIT_FAILED);
        }
        // 旧密码正确修改密码
        String newPassword = editPasswordDTO.getNewPassword();
        newPassword  = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        employee.setPassword(newPassword);
        updateById(employee);
    }
}
